package com.bodacn.packapp;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.appcompat.app.AppCompatActivity;

import android.speech.tts.TextToSpeech;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.json.JSONArray;
import org.json.JSONException;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.os.Environment.getDataDirectory;
import static android.os.Environment.getExternalStorageDirectory;

/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class MainActivity extends AppCompatActivity implements View.OnClickListener,
        FragmentA.FragmentACallBack,FragmentE.FragmentECallBack,FragmentMidBox.FragmentMidBoxCallBack,
        FragmentPrepBox.FragmentPrepBoxCallBack,FragmentMateBox.FragmentMateBoxCallBack
{
    private final static String TAG = MainActivity.class.getSimpleName();
    public static final int getParamFragmentA = 701;
    public static final int getParamFragmentB = 702;
    public static final int getParamFragmentC = 703;
    public static final int getParamFragmentD = 704;
    public static final int getParamFragmentE = 705;
    public static final int getParamFragmentF = 706;
    //全局变量
    String SaveFilePath="",SaveDBFolder="/DB";
    public static final String DB_Name ="bdmes.db";
    //全局变量
    String STORE_NAME = "Settings";
    //存放当前Fragment
    private Fragment mContent;
    private FragmentManager fragmentManager=getSupportFragmentManager();
    TextToSpeech textToSpeech;


    class FragmentStruct{
        Fragment frgmt;
        String ident;
    }
    private final List<FragmentStruct> mFragments=new ArrayList<FragmentStruct>();//fragment列表;
    private int curFragmentIndex = 0;//当前显示页面;
    //服务器地址
    String serviceUrl="http://172.20.10.11";
    String serviceUrlExt  = "/BDService.asmx?wsdl";
    String termNo="00000";
    String curLoginUserNo,curLoginUser,curFactory, curDepartNo,curDepart,packType,CPUID;//操作员所属部门等信息;
    int curOperateTime =600;//工作分钟
    int curPlaceCount=60;//工位数;
    //界面按钮;
    TextView txt_titleInv,txt_funcA,txt_funcB, txt_funcC, txt_funcD, txt_funcE,txt_funcF, txt_funcMidBox,txt_funcPrepBox,txt_funcMateBox, txt_funcBoxRule;
    Button btn_LoginUser, btn_LoginClose,btn_TermNo;
    ImageView titleImgView;
    Toast curToast;
    //拦截扫描枪输入部分
    String BarcodeStr="";
    long prScanSec=0;
    Boolean AllowScan=true;
    ScannerManager scannerManager;
    //用于将Activity中的参数传给Fragment
    private Map<String,Object> mParams=new HashMap<String,Object>();
    Ringtone ring;
    JSONArray curUserPower;

    //---------------------------接口申明及调用------------------------开始;
    //A:定义一个传参接口;
    public  interface OnTransParamsListenerA{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerA transParamsListenerA;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerA(OnTransParamsListenerA transParamsListener){
        this.transParamsListenerA=transParamsListener;
    }
    //B:定义一个传参接口;
    public  interface OnTransParamsListenerB{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerB transParamsListenerB;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerB(OnTransParamsListenerB transParamsListener){
        this.transParamsListenerB=transParamsListener;
    }
    //C:定义一个传参接口;
    public  interface OnTransParamsListenerC{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerC transParamsListenerC;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerC(OnTransParamsListenerC transParamsListener){
        this.transParamsListenerC=transParamsListener;
    }
    //D:定义一个传参接口;
    public  interface OnTransParamsListenerD{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerD transParamsListenerD;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerD(OnTransParamsListenerD transParamsListener){
        this.transParamsListenerD=transParamsListener;
    }
    //E:定义一个传参接口;
    public  interface OnTransParamsListenerE{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerE transParamsListenerE;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerE(OnTransParamsListenerE transParamsListener){
        this.transParamsListenerE=transParamsListener;
    }
    //F定义一个传参接口;
    public  interface OnTransParamsListenerF{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerF transParamsListenerF;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerF(OnTransParamsListenerF transParamsListener){
        this.transParamsListenerF=transParamsListener;
    }
    //F定义一个传参接口;
    public  interface OnTransParamsListenerMidBox{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerMidBox transParamsListenerMidBox;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerMidBox(OnTransParamsListenerMidBox transParamsListener){
        this.transParamsListenerMidBox=transParamsListener;
    }
    //F定义一个传参接口;
    public  interface OnTransParamsListenerPrepBox{
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerPrepBox transParamsListenerPrepBox;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerPrepBox(OnTransParamsListenerPrepBox transParamsListener){
        this.transParamsListenerPrepBox=transParamsListener;
    }

    //F定义一个传参接口;
    public  interface OnTransParamsListenerBoxRule {
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerBoxRule transParamsListenerBoxRule;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerBoxRule(OnTransParamsListenerBoxRule transParamsListener){
        this.transParamsListenerBoxRule =transParamsListener;
    }

    //F定义一个传参接口;
    public  interface OnTransParamsListenerMateBox {
        // 里面传个值@param Map<String,Object>适应多种类型;
        public void TransParams(Map<String, Object> mParams);
    }
    //2:对外公开的transParamsListener事件,配合接口及对外公布的事件;
    private OnTransParamsListenerMateBox transParamsListenerMateBox;
    //3:写一个对外公开的方法setTransParamsListener,供Fragment加接口监使用;
    public void setTransParamsListenerMateBox(OnTransParamsListenerMateBox transParamsListener){
        this.transParamsListenerMateBox =transParamsListener;
    }




    @Override
    public boolean dispatchKeyEvent(KeyEvent event) {

        if (event.getDeviceId() == -1) {
            System.out.println("event.getDeviceId()-return-"+event.getDeviceId());
            return super.dispatchKeyEvent(event);
        } else return scannerManager.dispatchKeyEvent(event);

    }

    @Override
    public void FragmentMateBoxWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentMateBoxWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
            if (paramComm=="TTS")
            {
                paramValue=Params.get("ParamValue").toString();
                textToSpeech.speak(paramValue, TextToSpeech.QUEUE_FLUSH, null);
            }
        }
    }

    @Override
    public void FragmentAWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentAWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
        }
    }


    //实现语音初始化构造函数
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            }
            else{
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }
    @Override
    public void FragmentEWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentEWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
            if (paramComm=="TTS")
            {
                paramValue=Params.get("ParamValue").toString();
                textToSpeech.speak(paramValue, TextToSpeech.QUEUE_ADD, null);
            }
        }
    }
    @Override
    public void FragmentMidBoxWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentMidBoxWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
            if (paramComm=="TTS")
            {
                paramValue=Params.get("ParamValue").toString();
                textToSpeech.speak(paramValue, TextToSpeech.QUEUE_FLUSH, null);
            }
        }
    }
    @Override
    public void FragmentPrepBoxWorkAndTransParams(Map<String, Object> Params) {
        //根据获取的参数，判断需要执行的事件;
        String paramComm,paramValue;
        //消息约定FragmentIndex，WorkCodeIndex，ParamObject;
        if (Params!=null)
        {
            System.out.println("FragmentPrepBoxWorkAndTransParams:"+Params);
            //根据参数调用相应功能;
            paramComm=Params.get("ParamComm").toString();
            if (paramComm=="AllowScan")
            {
                paramValue=Params.get("ParamValue").toString();
                Log.d("Main<-"+paramComm,paramValue);
                AllowScan=paramValue.equals("Y");
            }
            if (paramComm=="TTS")
            {
                paramValue=Params.get("ParamValue").toString();
                textToSpeech.speak(paramValue, TextToSpeech.QUEUE_FLUSH, null);
            }
            System.out.println("AllowScan:"+AllowScan);
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //全屏;
        //getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
        Uri notification = Uri.parse("android.resource://"+this.getPackageName()+"/"+R.raw.scan);
        ring = RingtoneManager.getRingtone(this, notification);
        try{
            //取存储路径;
            if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                //SD卡准备好的话，优先存储;
                SaveFilePath = getExternalStorageDirectory().toString();
                Log.d("msg","用存储卡:"+SaveFilePath);
            }
            else{
                //系统内部Flash;
                SaveFilePath =this.getFilesDir().toString();
                Log.d("msg","用系统目录:"+SaveFilePath);
            }
            //组织并判断是否需要创建Root目录;
            SaveFilePath = SaveFilePath +"/BDMES";
            Log.d("msg","存储目录为:"+SaveFilePath);
            //判断是否需要创建BDMES根目录;
            if (isExternalStorageWritable()==true) {
                //主目录;
                File file = new File(SaveFilePath);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath );
                //数据库目录
                file = new File(SaveFilePath +SaveDBFolder);
                if (!file.isDirectory()) file.mkdir();
                Log.d("msg","目录创建成功:"+ SaveFilePath +SaveDBFolder);
            }
            //设置页面;
            setContentView(R.layout.activity_main);
            //获取登陆参数
            Bundle paramBundle = this.getIntent().getExtras();
            curLoginUserNo=paramBundle.getString("LoginUserNo");
            curLoginUser=paramBundle.getString("LoginUser");
            curFactory=paramBundle.getString("CurFactory");
            curDepartNo=paramBundle.getString("CurDepartNo");
            curDepart=paramBundle.getString("CurDepart");
            curPlaceCount=paramBundle.getInt("CurPlaceCount");
            curOperateTime=paramBundle.getInt("OperateTime");
            serviceUrl=paramBundle.getString("serviceUrl");
            serviceUrlExt=paramBundle.getString("serviceUrlExt");
            packType=paramBundle.getString("packType");
            termNo=paramBundle.getString("termNo");
            CPUID=paramBundle.getString("CPUID");
            curUserPower=new JSONArray(paramBundle.getString("UserPower"));
            mParams.clear();
            mParams.put("ParamComm", "LoginParam");
            mParams.put("LoginUserNo", curLoginUserNo);
            mParams.put("LoginUser", curLoginUser);
            mParams.put("ServiceUrl",serviceUrl+serviceUrlExt);
            mParams.put("ServiceDir",serviceUrl);
            mParams.put("CPUID",CPUID);
            mParams.put("DepartNo",curDepartNo);
            mParams.put("Depart",curDepart);
            mParams.put("TermNo",termNo);
            System.out.println(paramBundle);

            //初始化按键，并将页面加载到fragment列表中;
            initView();
            //设置到第一个Fragment;
            loadDefaultFragment();
            //显示登陆员工;
            btn_LoginUser.setText(curLoginUser);
            btn_TermNo.setText(termNo);
            System.out.println("onCreate ------------------------setText---------2.3");
            //拦截扫描事件
            scannerManager = new ScannerManager(new ScannerManager.OnScanListener() {
                @Override
                public void onResult(String code,String deviceName) {
                    Log.d(TAG, "code= " + code);
                    playRingtone();
                    if (System.currentTimeMillis()-20000>prScanSec||AllowScan){
                        AllowScan=false;
                        sendParamFragmentBarcode(code);
                        prScanSec= System.currentTimeMillis();
                    }
                    else {
                        curToast.setText("扫描太快,请稍等");
                        curToast.show();
                    }
                }
            },this);
            textToSpeech=new TextToSpeech(this,new TTSListener());
            textToSpeech.setPitch(1.5f); // 在系统设置里也可以修改音调
        } catch (Exception e){
            Toast.makeText(this,String.valueOf("出错了，"+e.getMessage()),Toast.LENGTH_LONG).show();
        }
    }



    //插放音乐;
    private void playRingtone(){

        ring.play();


    }

    //传递参数到MainFragment
    private void sendParamFragmentBarcode(String paramBarcode) {
        Map<String,Object> lightParams=new HashMap<String,Object>();
        //Log.d("SendParam", "sendParamFragmentEConLight------------------Enter;");
        //Log.d("SendParam", "sendParamFragmentEConLight------------------1;");
        lightParams.clear();
        lightParams.put("ParamComm", "Barcode");
        lightParams.put("Barcode", paramBarcode);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentA")) transParamsListenerA.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentB")) transParamsListenerB.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentC")) transParamsListenerC.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentD")) transParamsListenerD.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentE")) transParamsListenerE.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentF")) transParamsListenerF.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentMidBox")) transParamsListenerMidBox.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentBoxRule")) transParamsListenerBoxRule.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentPrepBox")) transParamsListenerPrepBox.TransParams(lightParams);
        if (mFragments.get(curFragmentIndex).ident.equals("FragmentMateBox")) transParamsListenerMateBox.TransParams(lightParams);

    }


    //获取权限,默认都有;
    private int GetUserFuncPower(String paramFunc){
        if (curUserPower.length()>0)
        {
            for (int i=0;i<curUserPower.length();i++){
                if (curUserPower.optJSONObject(i).has(paramFunc)==true)
                {
                    try {
                        return curUserPower.optJSONObject(i).getInt(paramFunc);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
            return 0;
        }
        return 0;
    }
    @Override
    protected void onStart() {
        super.onStart();
        /*发参数到第一个Fragment*/
        sendParamFragmentA();

    }

    //根据顺序预加载Fragment
    private void loadDefaultFragment(){
        curFragmentIndex=-1;
        if (mFragments.size()>0) {
            FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
            Log.d("msg", "Add Fragment------------------------《预加载》");
            for (int i = mFragments.size() - 1; i >= 0; i--) {
                curFragmentIndex = i;
                Log.d("预加载", mFragments.get(curFragmentIndex).ident);
                mContent = mFragments.get(curFragmentIndex).frgmt;
                fragmentTransaction.add(R.id.mFragmentContainer, mContent);
                fragmentTransaction.hide(mContent);
            }
            //提交修改并显示;
            fragmentTransaction.show(mContent);
            fragmentTransaction.commit();

        }
    }

    //Fragment切换

    public void switchFragment(Fragment from, String toFrgmtName) {
        Fragment to=null;
        for (int i=0;i<mFragments.size();i++)
        {
            if (mFragments.get(i).ident.equals(toFrgmtName)==true)
            {
                to=mFragments.get(i).frgmt;
                curFragmentIndex=i;
                break;
            }
        }
        if ((mContent != to)&&(to!=null)) {
            mContent = to;
            FragmentTransaction transaction = fragmentManager.beginTransaction().setCustomAnimations(
                    android.R.anim.slide_in_left,android.R.anim.slide_out_right);
            if (!to.isAdded()) {    // 先判断是否被add过
                transaction.hide(from).add(R.id.mFragmentContainer, to).commit(); // 隐藏当前的fragment，add下一个到Activity中
            } else {
                transaction.hide(from).show(to).commit(); // 隐藏当前的fragment，显示下一个
            }
        }

    }


    //加载需要用到的Fragment
    private boolean AddFragment(String paramFrgmtName){
        //创建Fragment;
        FragmentStruct tmpFrgmtStruct=new FragmentStruct();
        try {
            Log.d("AddFragment",paramFrgmtName+"--Start");
            tmpFrgmtStruct.frgmt=(Fragment) Class.forName(getPackageName()+"."+paramFrgmtName).newInstance();
            tmpFrgmtStruct.ident=paramFrgmtName;
            mFragments.add(tmpFrgmtStruct);
            Log.d("AddFragment",paramFrgmtName+"--Over");
            return true;
        }catch (ClassNotFoundException err){
            err.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        }
        return  false;//未成功加载
    }

    private void initView() {
        txt_titleInv = (TextView) findViewById(R.id.txt_titleInv);
        //顶端图标;
        titleImgView = (ImageView) findViewById(R.id.titleImgView);
        titleImgView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //将临时文件复制到SD卡;
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    Log.d("MSG-getDatabasePath", getDatabasePath(DB_Name).toString());
                    Log.d("MSG-getDataDirectory", getDataDirectory().toString());
                    Log.d("MSG-StorageDirectory", getExternalStorageDirectory().toString());
                    //将数据复制到SD卡;
                    copyFile(getDatabasePath(DB_Name).toString(), SaveFilePath + SaveDBFolder + "/" + DB_Name);
                    copyFolder(getCacheDir().toString(), SaveFilePath);
                }

            }
        });
        titleImgView.setOnLongClickListener(new View.OnLongClickListener() {
            @Override
            public boolean onLongClick(View v) {
                AlertDialog alertDialog = new AlertDialog.Builder(v.getContext())
                        .setTitle("系统提示").setMessage("您确定要从临时数据复制到外部存储中吗？")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                //将临时文件复制到SD卡;
                                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                                    Log.d("MSG-getDatabasePath", getDatabasePath(DB_Name).toString());
                                    Log.d("MSG-getDataDirectory", getDataDirectory().toString());
                                    Log.d("MSG-StorageDirectory", getExternalStorageDirectory().toString());
                                    //将SD卡数据复制到数据目录;
                                    //copyFile(SaveFilePath+SaveDBFolder+"/"+DB_Name,getDatabasePath(DB_Name).toString());
                                    copyFile(getDatabasePath(DB_Name).toString(), SaveFilePath + SaveDBFolder + "/" + DB_Name);
                                }
                            }

                        }).setNegativeButton("取消",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(DialogInterface dialog, int which) {
                                        return;
                                    }
                                }).create(); // 创建对话框
                alertDialog.show(); // 显示对话框
                return false;
            }
        });
        //下边栏按钮
        txt_funcA = (TextView) findViewById(R.id.txt_funcA);
        txt_funcB = (TextView) findViewById(R.id.txt_funcB);
        txt_funcC = (TextView) findViewById(R.id.txt_funcC);
        txt_funcD = (TextView) findViewById(R.id.txt_funcD);
        txt_funcE = (TextView) findViewById(R.id.txt_funcE);
        txt_funcF = (TextView) findViewById(R.id.txt_funcF);
        txt_funcMidBox = (TextView) findViewById(R.id.txt_funcMidBox);
        txt_funcPrepBox = (TextView) findViewById(R.id.txt_funcPrepBox);
        txt_funcBoxRule = (TextView) findViewById(R.id.txt_funcBoxRule);
        txt_funcMateBox= (TextView) findViewById(R.id.txt_funcMateBox);
        //设置监听;
        txt_funcA.setOnClickListener(this);
        txt_funcB.setOnClickListener(this);
        txt_funcC.setOnClickListener(this);
        txt_funcD.setOnClickListener(this);
        txt_funcE.setOnClickListener(this);
        txt_funcF.setOnClickListener(this);
        txt_funcMidBox.setOnClickListener(this);
        txt_funcPrepBox.setOnClickListener(this);
        txt_funcBoxRule.setOnClickListener(this);
        txt_funcMateBox.setOnClickListener(this);

        //退出
        btn_LoginUser = (Button) findViewById(R.id.btn_LoginUser);
        btn_LoginClose = (Button) findViewById(R.id.btn_LoginClose);
        btn_LoginClose.setOnClickListener(this);
        btn_TermNo = (Button) findViewById(R.id.btn_TermNo);
        //初始提醒;
        curToast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_LONG);
        curToast.setGravity(Gravity.CENTER, 0, 0);
        //创建Fragment;
        if (GetUserFuncPower("FuncA") == 1) {
            txt_funcA.setVisibility(View.VISIBLE);
            AddFragment("FragmentA");
        } else txt_funcA.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncB") == 1) {
            txt_funcB.setVisibility(View.VISIBLE);
            AddFragment("FragmentB");
        } else txt_funcB.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncC") == 1) {
            txt_funcC.setVisibility(View.VISIBLE);
            AddFragment("FragmentC");
        } else txt_funcC.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncD") == 1) {
            txt_funcD.setVisibility(View.VISIBLE);
            AddFragment("FragmentD");
        } else txt_funcD.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncE") == 1) {
            txt_funcE.setVisibility(View.VISIBLE);
            AddFragment("FragmentE");
        } else txt_funcE.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncF") == 1) {
            txt_funcF.setVisibility(View.VISIBLE);
            AddFragment("FragmentF");
        } else txt_funcF.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncMidBox") == 1) {
            txt_funcMidBox.setVisibility(View.VISIBLE);
            AddFragment("FragmentMidBox");
        } else txt_funcMidBox.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncBoxRule") == 1) {
            txt_funcBoxRule.setVisibility(View.VISIBLE);
            AddFragment("FragmentBoxRule");
        } else txt_funcBoxRule.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncPrepBox") == 1) {
            txt_funcPrepBox.setVisibility(View.VISIBLE);
            AddFragment("FragmentPrepBox");
        } else txt_funcPrepBox.setVisibility(View.GONE);
        if (GetUserFuncPower("FuncMateBox") == 1) {
            txt_funcMateBox.setVisibility(View.VISIBLE);
            AddFragment("FragmentMateBox");
        } else txt_funcMateBox.setVisibility(View.GONE);

    }

    //传递参数到MainFragment
    private void sendParamFragmentA() {
        Log.d("SendParam", "sendParamFragmentA------------------Enter;");
        if (transParamsListenerA != null) {
            Log.d("SendParam", "sendParamFragmentA------------------1;");
            transParamsListenerA.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentA------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentB() {
        Log.d("SendParam", "sendParamFragmentB------------------Enter;");
        if (transParamsListenerB != null) {
            Log.d("SendParam", "sendParamFragmentB------------------1;");
            transParamsListenerB.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentB------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentC() {
        Log.d("SendParam", "sendParamFragmentC------------------Enter;");
        if (transParamsListenerC != null) {
            Log.d("SendParam", "sendParamFragmentC------------------1;");
            transParamsListenerC.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentC------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentD() {
        Log.d("SendParam", "sendParamFragmentD------------------Enter;");
        if (transParamsListenerD != null) {
            Log.d("SendParam", "sendParamFragmentD------------------1;");
            transParamsListenerD.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentD------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentE() {
        Log.d("SendParam", "sendParamFragmentE------------------Enter;");
        if (transParamsListenerE != null) {
            Log.d("SendParam", "sendParamFragmentE------------------1;");
            transParamsListenerE.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentE------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentF() {
        Log.d("SendParam", "sendParamFragmentF------------------Enter;");
        if (transParamsListenerF != null) {
            Log.d("SendParam", "sendParamFragmentF------------------1;");
            transParamsListenerF.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentF------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentMidBox() {
        Log.d("SendParam", "sendParamFragmentMidBox------------------Enter;");
        if (transParamsListenerMidBox != null) {
            Log.d("SendParam", "sendParamFragmentMidBox------------------1;");
            transParamsListenerMidBox.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentMidBox------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentPrepBox() {
        Log.d("SendParam", "sendParamFragmentPrepBox------------------Enter;");
        if (transParamsListenerPrepBox != null) {
            Log.d("SendParam", "sendParamFragmentPrepBox------------------1;");
            transParamsListenerPrepBox.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentPrepBox------------------2;");
        }
    }
    //传递参数到MainFragment
    private void sendParamFragmentBoxRule() {
        Log.d("SendParam", "sendParamFragmentBoxRule------------------Enter;");
        if (transParamsListenerBoxRule != null) {
            Log.d("SendParam", "sendParamFragmentBoxRule------------------1;");
            transParamsListenerBoxRule.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentBoxRule------------------2;");
        }
    }

    //传递参数到MainFragment
    private void sendParamFragmentMateBox() {
        Log.d("SendParam", "sendParamFragmentMateRule------------------Enter;");
        if (transParamsListenerMateBox != null) {
            Log.d("SendParam", "sendParamFragmentMateRule------------------1;");
            transParamsListenerMateBox.TransParams(mParams);
            Log.d("SendParam", "sendParamFragmentMateRule------------------2;");
        }
    }


    /**
     * 定义一个Handler用于接收Fragment给Activity发出来的指令
     */
    public Handler mainHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                switch (msg.what) {
                    case getParamFragmentA:

                        break;
                    case getParamFragmentB:

                        break;
                    case getParamFragmentC:

                        break;
                    case getParamFragmentD:
                        //mViewPager.setCurrentItem(0,true);
                        break;
                    case getParamFragmentE:
                        //mViewPager.setCurrentItem(1,true);
                        break;
                    case getParamFragmentF:
                        //mViewPager.setCurrentItem(2,true);
                        break;
                    default:
                        break;
                }
            }
        }
    };

    //获取当前显示的Fragment
    public Fragment getVisibleFragment() {
        FragmentManager fragmentManager;
        fragmentManager = MainActivity.this.getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return fragment;
        }
        return null;
    }

    //重置所有文本的选中状态
    public void unSelected(){

        txt_funcA.setSelected(false);
        txt_funcA.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcB.setSelected(false);
        txt_funcB.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcC.setSelected(false);
        txt_funcC.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcD.setSelected(false);
        txt_funcD.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcE.setSelected(false);
        txt_funcE.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcF.setSelected(false);
        txt_funcF.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcMidBox.setSelected(false);
        txt_funcMidBox.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcPrepBox.setSelected(false);
        txt_funcPrepBox.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcBoxRule.setSelected(false);
        txt_funcBoxRule.setTextColor(getResources().getColor(R.color.text_gray));
        txt_funcMateBox.setSelected(false);
        txt_funcMateBox.setTextColor(getResources().getColor(R.color.text_gray));
    }
    public void Selected(TextView paramBtn){
        paramBtn.setSelected(true);
        paramBtn.setTextColor(getResources().getColor(R.color.text_blue));
        txt_titleInv.setText(paramBtn.getText());
    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.txt_funcA:
                unSelected();
                Selected(txt_funcA);
                curFragmentIndex=0;
                switchFragment(mContent,"FragmentA");
                sendParamFragmentA();
                break;
            case R.id.txt_funcB:
                unSelected();
                Selected(txt_funcB);
                curFragmentIndex=1;
                switchFragment(mContent,"FragmentB");
                sendParamFragmentB();
                break;
            case R.id.txt_funcC:
                unSelected();
                Selected(txt_funcC);
                curFragmentIndex=2;
                switchFragment(mContent,"FragmentC");
                sendParamFragmentC();
                break;
            case R.id.txt_funcD:
                unSelected();
                Selected(txt_funcD);
                curFragmentIndex=3;
                switchFragment(mContent,"FragmentD");
                sendParamFragmentD();
                break;
            case R.id.txt_funcE:
                unSelected();
                Selected(txt_funcE);
                curFragmentIndex=4;
                switchFragment(mContent,"FragmentE");
                sendParamFragmentE();
                break;
            case R.id.txt_funcF:
                unSelected();
                Selected(txt_funcF);
                curFragmentIndex=5;
                switchFragment(mContent,"FragmentF");
                sendParamFragmentF();
                break;
            case R.id.txt_funcMidBox:
                unSelected();
                Selected(txt_funcMidBox);
                curFragmentIndex=6;
                switchFragment(mContent,"FragmentMidBox");
                sendParamFragmentMidBox();
                break;
            case R.id.txt_funcBoxRule:
                unSelected();
                Selected(txt_funcBoxRule);
                curFragmentIndex=7;
                switchFragment(mContent,"FragmentBoxRule");
                sendParamFragmentBoxRule();
                break;
            case R.id.txt_funcPrepBox:
                unSelected();
                Selected(txt_funcPrepBox);
                switchFragment(mContent,"FragmentPrepBox");
                sendParamFragmentPrepBox();
                break;
            case R.id.txt_funcMateBox:
                unSelected();
                Selected(txt_funcMateBox);
                switchFragment(mContent,"FragmentMateBox");
                sendParamFragmentMateBox();
                break;
            case R.id.btn_LoginClose:
                finish();//关闭当前Activity，返回上一级;
                break;
        }
    }

    //判断外部存储是否可读写
    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d("msg","MainActivity OnDestroy------------------------");
    }



    /**
     * 复制单个文件
     * @param oldPath String 原文件路径 如：c:/fqf.txt
     * @param newPath String 复制后路径 如：f:/fqf.txt
     * @return boolean
     */
    public void copyFile(String oldPath, String newPath) {
        try {
            int bytesum = 0;
            int byteread = 0;
            File oldfile = new File(oldPath);
            if (oldfile.exists()) { //文件存在时
                InputStream inStream = new FileInputStream(oldPath); //读入原文件
                FileOutputStream fs = new FileOutputStream(newPath);
                byte[] buffer = new byte[1444];
                int length;
                while ( (byteread = inStream.read(buffer)) != -1) {
                    bytesum += byteread; //字节数 文件大小
                    System.out.println(bytesum);
                    fs.write(buffer, 0, byteread);
                }
                inStream.close();
            }
        }
        catch (Exception e) {
            System.out.println("复制单个文件操作出错");
            e.printStackTrace();

        }

    }

    /**
     * 复制整个文件夹内容
     * @param oldPath String 原文件路径 如：c:/fqf
     * @param newPath String 复制后路径 如：f:/fqf/ff
     * @return boolean
     */
    public void copyFolder(String oldPath, String newPath) {

        try {
            (new File(newPath)).mkdirs(); //如果文件夹不存在 则建立新文件夹
            File a=new File(oldPath);
            String[] file=a.list();
            File temp=null;
            for (int i = 0; i < file.length; i++) {
                if(oldPath.endsWith(File.separator)){
                    temp=new File(oldPath+file[i]);
                }
                else{
                    temp=new File(oldPath+File.separator+file[i]);
                }

                if(temp.isFile()){
                    FileInputStream input = new FileInputStream(temp);
                    FileOutputStream output = new FileOutputStream(newPath + "/" +
                            (temp.getName()).toString());
                    byte[] b = new byte[1024 * 5];
                    int len;
                    while ( (len = input.read(b)) != -1) {
                        output.write(b, 0, len);
                    }
                    output.flush();
                    output.close();
                    input.close();
                }
                if(temp.isDirectory()){//如果是子文件夹
                    copyFolder(oldPath+"/"+file[i],newPath+"/"+file[i]);
                }
            }
        }
        catch (Exception e) {
            System.out.println("复制整个文件夹内容操作出错");
            e.printStackTrace();

        }

    }
}
